package com.youan.pangu.security.brower.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.youan.pangu.base.bean.GlobalValue;
import com.youan.pangu.base.bean.result.SuccessResponse;
import com.youan.pangu.base.util.ResponseUtil;
import com.youan.pangu.security.bean.LoginInfor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: 辛晟昊
 * @time: 2020/3/8 16:19
 */
@Component
public class PanguSuccessAuthenticationHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    private Logger logger = LoggerFactory.getLogger(GlobalValue.LOOGER_NAME);

    private RequestCache requestCache = new HttpSessionRequestCache();
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        SavedRequest savedRequest = requestCache.getRequest(httpServletRequest, httpServletResponse);

        if(null == savedRequest) {
            responseValue(httpServletResponse, authentication);
            return;
        }

        String targetUrl = savedRequest.getRedirectUrl();
        if(targetUrl.endsWith(".html")){
            super.onAuthenticationSuccess(httpServletRequest, httpServletResponse, authentication);
        }else {
            logger.error("目标链接<{}>的返回未实现", targetUrl);
        }

    }

    private void responseValue(HttpServletResponse httpServletResponse, Authentication authentication) throws JsonProcessingException {

        LoginInfor loginInfor = (LoginInfor) authentication.getPrincipal();

        // 获取用户的详细信息，菜单权限
        SuccessResponse successResponse = new SuccessResponse(loginInfor);

        ResponseUtil.write(httpServletResponse, objectMapper.writeValueAsString(successResponse));
    }
}
